<template>
  <div class="createPost-container">
    <sticky :className="'sub-navbar'" :z-index="$upZindex">

      <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="back">{{$t('table.back')}}
      </el-button>


    </sticky>

    <el-form class="form-container" :model="postForm" :rules="rules" ref="postForm" label-position="right" label-width="150px" style='width: 60%; margin-left:10px;margin-top:20px;'>



      <div class="divide-line">合同信息</div>
      <el-form-item label="合同名称" prop="contractName">
        {{postForm.contractName}}
      </el-form-item>

      <el-form-item label="合同类型" prop="contractType">
        {{postForm.contractType | $contractTypeFilter}}
      </el-form-item>

      <el-form-item label="版权引入合同编号" v-if="postForm.contractType==='OUT'" prop="contractInNo">
        {{postForm.contractInNo}}

      </el-form-item>

      <el-form-item label="合同编号" prop="contractNo">
        {{postForm.contractNo}}
      </el-form-item>



      <el-form-item label="协议有效期(月)" prop="mounthNum">
        {{postForm.mounthNum}}
      </el-form-item>


      <el-form-item label="开始时间" prop="beginDate">
          {{postForm.beginDate | $dateConvert}}
      </el-form-item>

      <el-form-item label="终止时间" prop="endDate">
          {{postForm.endDate | $dateConvert}}
      </el-form-item>


      <el-form-item label="签约方数量" prop="contractNum">
        {{postForm.contractNum | $partyFilter}}
      </el-form-item>


      <el-form-item label="甲方" prop="partyOne">
        {{postForm.partyOne}}
      </el-form-item>
      <el-form-item label="乙方" prop="partyTwo">
        {{postForm.partyTwo}}
      </el-form-item>
      <el-form-item label="丙方" v-if="postForm.contractNum=='3'" prop="partyThree">
        {{postForm.partyThree}}
      </el-form-item>



      <el-form-item label="合作供应商" prop="supplyName">
        {{postForm.supplyName}}
      </el-form-item>



      <div class="divide-line">通讯信息</div>
      <el-form-item label="联系方式" prop="linkMobile">
        {{postForm.linkMobile}}
      </el-form-item>
      <el-form-item label="地址邮编" prop="address">
        {{postForm.address}}
      </el-form-item>

      <el-form-item label="签约责编" prop="signName">
        {{postForm.signName}}
      </el-form-item>

      <div class="divide-line">结算信息</div>
      <el-form-item label="营业执照/身份证" prop="certNo">

        {{postForm.certNo}}

      </el-form-item>

      <el-form-item label="" prop="appendixAddress">



        <el-upload
          class="avatar-uploader"
          :action="uploadImgUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          accept="image/*"
          :disabled="opt==='info'">
          <img v-if="postForm.appendixAddress" :src="appendixImgSrc" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

          <div class="avatar-uploader-text">{{postForm.appendixFileName}}</div>
          <div v-if="postForm.appendixAddress" class="avatar-uploader-text"><el-button type="warning" icon="el-icon-download" @click="downloadAppendixFile" circle></el-button></div>

      </el-form-item>

      <!-- 预览 -->
      <cd-img ref="img"
              :imgList="imgList"
              :index="currentIndex"></cd-img>



      <el-form-item label="账户名" prop="accountName">
        {{postForm.accountName}}
      </el-form-item>
      <el-form-item label="开户行" prop="bankName">
        {{postForm.bankName}}
      </el-form-item>
      <el-form-item label="账号" prop="bankNo">
        {{postForm.bankNo}}
      </el-form-item>
      <el-form-item label="结算形式" prop="balanceType">
        {{postForm.balanceType | $balanceTypeAllFilter}}
      </el-form-item>


      <el-form-item :label="amountLabelMap[postForm.balanceType]" v-if="postForm.balanceType!='DIVIDE'" prop="totalAmount">
        {{postForm.totalAmount}}
      </el-form-item>

      <div v-if="postForm.balanceType!='BUY' && postForm.balanceType!='MixClear'">
        <el-form-item label="甲方比例" prop="partyOneNum">
          {{postForm.partyOneNum}}
        </el-form-item>
        <el-form-item label="乙方比例" prop="partyTwoNum">
          {{postForm.partyTwoNum}}
        </el-form-item>
        <el-form-item v-if="postForm.contractNum==3" label="丙方比例" prop="partyThreeNum">
          {{postForm.partyThreeNum}}
        </el-form-item>
      </div>


      <el-form-item label="结算说明" prop="balanceRemark">
        {{postForm.balanceRemark}}
      </el-form-item>


    </el-form>

    <div class="divide-line">附件文档</div>


    <div class="appendix_project">
      <el-upload
        :action="uploadImgUrl"
        list-type="picture-card"
        :file-list="fileList"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-remove="handleBeforeRemove"
        :on-success="handleAppraisesSuccess"
        :limit="10"
        :on-exceed="handleExceed"
        style="margin-left:150px"
        :disabled="true"
      >
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img height="300px" :src="dialogImageUrl" alt="">
      </el-dialog>

      <div class="appendix_name_div">
        <span v-for="(appendixProject,index) in postForm.appendixProjects" class="appendix_name" :key="index">
          {{appendixProject.appendixName}}
        </span>
      </div>
    </div>

    <div v-if="opt==='info'">
      <div class="divide-line-long">版权信息</div>
      <CopyrightsList :contractNo="postForm.contractNo"></CopyrightsList>

      <div class="divide-line-long">授权信息</div>
      <ContractRigthsList :contractNo="postForm.contractNo"></ContractRigthsList>


      <div v-if="postForm.contractStatus==='VALID'" style="margin-bottom: 30px" align="center">

        <el-button v-if="postForm.contractType === 'IN'" v-has="'supplyContractInTable_edit'" type="primary" size="large" @click="handleUpdate">{{$t('table.edit')}}合同</el-button>
        <el-button v-else-if="postForm.contractType === 'OUT'" v-has="'supplyContractOutTable_edit'" type="primary" size="large" @click="handleUpdate">{{$t('table.edit')}}合同</el-button>
        <!--<el-button type="danger" size="large" @click="handleInvalid">{{$t('table.invalid')}}</el-button>-->
      </div>
    </div>

  </div>


</template>


<script>
  import Sticky from '@/components/Sticky' // 粘性header组件
  import { infoSupplyContract, createSupplyContract, updateSupplyContract, fetchSupplyList, checkContractDate, fetchContractList } from '@/api/supplyContract/supplyContract'
  import CopyrightsList from '@/views/components/CopyrightsList'
  import ContractRigthsList from '@/views/components/ContractRigthsList'
  import CdImg from '@/views/components/CdImg'

  import excel_img from '@/assets/icon_imgs/excel.png'
  import pdf_img from '@/assets/icon_imgs/pdf.png'
  import ppt_img from '@/assets/icon_imgs/ppt.png'
  import word_img from '@/assets/icon_imgs/word.png'
  import file_img from '@/assets/icon_imgs/file.png'
  import txt_img from '@/assets/icon_imgs/txt.png'

  const defaultForm = {
    code: ''
  }

  export default {
    name: 'contractdetail',
    components: { Sticky, CopyrightsList, ContractRigthsList, CdImg },
    // components: { Sticky, CopyrightsList },
    data() {
      return {
        postForm: Object.assign({
          balanceType: 'BUY',
          contractType: 'IN',
          contractNum: '2',
          appendixAddress: '',
          appendixProjects: [{}]
        }, defaultForm),
        loading: false,
        rules: {
        },
        listQuery: {
          compoundSearch: undefined,
          expireStatus: undefined,
          clearMethod: undefined,
          contractType: undefined
        },
        amountLabelMap: {
          BUY: '买断金额',
          PrePayDivide: '预付金额',
          MixClear: '涉及金额',
          DIVIDE: '无金额'
        },
        oldContractInNo: '',
        disabled: false,
        opt: '',
        imageUrl: '',
        imgList: [],
        currentIndex: 0,
        uploadImgUrl: process.env.BASE_API + '/upload/doUploadFile.do',
        dialogImageUrl: '',
        dialogVisible: false,
        // fileList: ["http://pc76aozjb.bkt.clouddn.com/word.png","http://pc76aozjb.bkt.clouddn.com/word.png"]
        fileList: [],
        contractTable: 'supplyContractInTable',
        appendixImgSrc: '',
        appendixFileType: ''
      }
    },
    computed: {
      contentShortLength() {
        return this.postForm.content_short.length
      }
    },
    created() {
      const id = this.$route.query.id
      const contractNo = this.$route.query.contractNo

      const supplyId = this.$route.query.supplyId
      const supplyName = this.$route.query.supplyName

      if (id != null || contractNo != null) {
        const params = { 'id': id, 'contractNo': contractNo }
        infoSupplyContract(params).then(response => {
          if (response.success) {
            this.postForm = Object.assign({}, response.content) // copy obj
            // 记录老合同号用于比较
            this.oldContractInNo = this.postForm.contractInNo
            // 判断是否是详情页面
            this.opt = this.$route.query.opt
            if (this.opt === 'info') {
              this.disabled = true
            }
            // 初始化附件图片
            this.initAppendix(response.content.appendixFileName, response.content.appendixAddress)
            // 图片墙
            this.buildPicWall(response.content.appendixProjects)
            if (this.postForm.contractType === 'OUT') {
              this.contractTable = 'supplyContractOutTable'
            }
          } else {
            this.$message({
              type: 'fail',
              message: 'response.message'
            })
            this.history.go(-1)
          }
        })
      }

      if (supplyName && supplyId) {
        this.postForm.supplyId = supplyId
        this.postForm.supplyName = supplyName
      }
    },
    filters: {
    },
    methods: {
      submitForm() {},
      createData() {
        this.$refs['postForm'].validate((valid) => {
          if (valid) {
            // 根据是否有id来判断
            if (this.postForm.id != null) {
              updateSupplyContract(this.postForm).then(response => {
                if (response.success) {
                  this.$notify({
                    title: '成功',
                    message: '更新成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({ name: this.contractTable })
                } else {
                  this.$message({
                    type: 'fail',
                    message: response.message
                  })
                }
              })
            } else {
              createSupplyContract(this.postForm).then((response) => {
                if (response.success) {
                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({ name: this.contractTable })
                } else {
                  this.$message({
                    type: 'fail',
                    message: response.message
                  })
                }
              })
            }
          }
        })
      },
      querySearchAsync(queryString, callback) {
        var list = [{}]
        // 调用的后台接口
        // let url = 后台接口地址 + queryString;
        // 从后台获取到对象数组
        const params = { 'abbreviation': queryString }
        fetchSupplyList(params).then((response) => {
          if (response.success) {
            // 在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
            for (const i of response.content) {
              // 将名字放入
              Object.assign(i, { 'value': i.abbreviation })
            }
            list = response.content
            console.info(list)
            callback(list)
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      // 供应商选择后的回调
      handleSelect(item) {
        // 供应商id
        this.postForm.supplyId = item.id
        this.postForm.supplyName = item.abbreviation
      },
      queryContractIn(queryString, callback) {
        var list = [{}]
        // 调用的后台接口
        // let url = 后台接口地址 + queryString;
        // 从后台获取到对象数组
        const params = { 'contractNo': this.postForm.contractInNo }

        fetchContractList(params).then((response) => {
          if (response.success) {
            // 在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
            for (const i of response.content) {
              // 将名字放入
              Object.assign(i, { 'value': i.contractNo })
            }

            list = response.content

            callback(list)
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      // 供应商选择后的回调
      handleContractSelect(item) {
        // 校验
        this.checkContractDate()
      },
      checkContractDate() {
        if (this.postForm.contractInNo === null || this.postForm.contractInNo === '' || this.postForm.contractInNo === this.oldContractInNo) {
          return
        }
        const params = { 'contractNo': this.postForm.contractInNo }

        checkContractDate(params).then((response) => {
          if (response.success) {
            if (!response.success) {
              this.$message(response.message)
              this.postForm.contractInNo = ''
            }
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      handleUpdate() {
        let routeName = 'supplyContractOutEdit'
        if (this.postForm.contractType === 'IN') {
          routeName = 'supplyContractInEdit'
        }
        this.$router.push({ name: routeName, query: { id: this.postForm.id }})
      },
      // handleInvalid() {
      //   this.$confirm('失效后，该条数据不可操作，确认失效?', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then((response) => {
      //     // 调用失效接口
      //     var p = { id: this.postForm.id }
      //     invalidSupplyContract(p).then(response => {
      //       if (response.success) {
      //         this.$message({
      //           type: 'success',
      //           message: '操作成功!'
      //         })
      //         this.$router.push({ name: this.contractTable })
      //       } else {
      //         this.$message({
      //           type: 'fail',
      //           message: response.message
      //         })
      //       }
      //     })
      //   }).catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消操作'
      //     })
      //   })
      // },
      // 图片上传相关
      handleAvatarSuccess(response, file) {
        if (response.success) {
          this.imageUrl = response.content
          this.postForm.appendixAddress = response.content
        }
      },
      beforeAvatarUpload(file) {
        const fileType = file.type
        // const isLt2M = file.size / 1024 / 1024 < 2;

        const flag = /\.*(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileType)
        if (!flag) {
          this.$message.error('图片类型必须是.gif,jpeg,jpg,png中的一种!')
        } else {
          this.postForm.appendixFileName = file.name
        }
        return flag
      },
      large(img, index) { // 图片放大
        if (img.length > 0 && this.opt === 'info') {
          this.imgList.push(img)
          this.currentIndex = index
          this.$refs.img.open()
        }
      },
      handleBeforeRemove(file, fileList) {
        this.postForm.appendixProjects.splice(fileList.indexOf(file), 1)
      },
      handleRemove(file, fileList) {
        // fileList.indexOf(file)
        this.fileList = fileList
      },
      handlePictureCardPreview(file) {
        const appendixProject = this.postForm.appendixProjects[this.fileList.indexOf(file)]

        const appendixType = appendixProject.appendixType
        if (appendixType === 'IMG') {
          // this.dialogImageUrl = file.url;
          this.dialogImageUrl = file.url
          this.dialogVisible = true
        } else {
          window.open(appendixProject.appendixAddress)
        }
      },

      handleAppraisesSuccess(response, file) {
        console.info(this.fileList)
        if (response.success) {
          var fileName = file.name
          var split = fileName.split('.')
          var fileType = split[split.length - 1].toUpperCase()
          // 判断类型展示图片墙
          var pic = { name: fileName, url: response.content }
          var appendixType = 'IMG'
          if (fileType === 'BMP' || fileType === 'JPG' || fileType === 'JPEG' || fileType === 'PNG' || fileType === 'GIF') {
            console.info('')
          } else if (fileType === 'DOC' || fileType === 'DOCX') {
            pic.url = word_img
            appendixType = 'WORD'
          } else if (fileType === 'PDF') {
            pic.url = pdf_img
            appendixType = 'PDF'
          } else if (fileType === 'PPT' || fileType === 'PPTX') {
            pic.url = ppt_img
            appendixType = 'PPT'
          } else if (fileType === 'XLSX' || fileType === 'XLS') {
            pic.url = excel_img
            appendixType = 'EXCEL'
          } else if (fileType === 'TXT') {
            pic.url = txt_img
            appendixType = 'TXT'
          } else {
            pic.url = file_img
            appendixType = 'FILE'
          }
          // this.imageUrl = response.content;
          // this.postForm.appendixAddress = response.content;
          this.fileList.push(pic)
          this.dialogImageUrl = pic.url
          // 附件列表添加
          var appendixItem = {
            appendixType: appendixType,
            appendixName: fileName,
            appendixAddress: response.content
          }
          if (!this.postForm.appendixProjects) {
            this.postForm.appendixProjects = [appendixItem]
          } else {
            this.postForm.appendixProjects.push(appendixItem)
          }
        } else {
          this.$message({
            type: 'fail',
            message: '上传失败!'
          })
        }
      },
      initAppendix(appendixFileName, appendixAddress) {
        if (appendixFileName && appendixAddress) {
          const split = appendixFileName.split('.')
          const fileType = split[split.length - 1].toUpperCase()

          if (fileType === 'BMP' || fileType === 'JPG' || fileType === 'JPEG' || fileType === 'PNG' || fileType === 'GIF') {
            this.appendixImgSrc = appendixAddress
            this.appendixFileType = 'IMG'
          } else if (fileType === 'DOC' || fileType === 'DOCX') {
            this.appendixImgSrc = word_img
            this.appendixFileType = 'WORD'
          } else if (fileType === 'PDF') {
            this.appendixImgSrc = pdf_img
            this.appendixFileType = 'PDF'
          } else if (fileType === 'PPT' || fileType === 'PPTX') {
            this.appendixImgSrc = ppt_img
            this.appendixFileType = 'PPT'
          } else if (fileType === 'XLSX' || fileType === 'XLS') {
            this.appendixImgSrc = excel_img
            this.appendixFileType = 'EXCEL'
          } else if (fileType === 'TXT') {
            this.appendixImgSrc = txt_img
            this.appendixFileType = 'TXT'
          } else {
            this.appendixImgSrc = file_img
            this.appendixFileType = 'FILE'
          }
        }
      },
      buildPicWall(appendixProjects) {
        for (const appendix of appendixProjects) {
          // const id = appendix.id
          const appendixName = appendix.appendixName
          const appendixType = appendix.appendixType
          const appendixAddress = appendix.appendixAddress

          var pic = { name: appendixName, url: '' }
          if (appendixType === 'IMG') {
            pic.url = appendixAddress
          } else if (appendixType === 'WORD') {
            pic.url = word_img
          } else if (appendixType === 'PDF') {
            pic.url = pdf_img
          } else if (appendixType === 'PPT') {
            pic.url = ppt_img
          } else if (appendixType === 'EXCEL') {
            pic.url = excel_img
          } else if (appendixType === 'TXT') {
            pic.url = txt_img
          } else {
            pic.url = file_img
          }
          this.fileList.push(pic)
        }
      },
      handleExceed(files, fileList) {
        this.$message.warning('最多允许上传10个附件')
      },
      // 返回
      back() {
        // this.$router.push({ name: this.contractTable })
        history.go(-1)
      },
      downloadAppendixFile() {
        window.open(this.postForm.appendixAddress)
      }

    },
    watch: {
      '$route'(to, from) {
        if (from.name === 'supplyContractInfo') {
          this.$router.go(0)
        }
      }
    }
  }
</script>

<style scoped>
  /*使用 >>>可以在已经写了scoped的style下控制样式*/
  /*>>>样式穿透，不受scoped限制*/
  .avatar-uploader >>> .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader >>> .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 250px;
    height: 300px;
    line-height: 300px;
    text-align: center;
  }
  .avatar-uploader-text {
    width: 250px;
    text-align: center;
  }

  .avatar {
    width: 250px;
    height: 300px;
    display: block;
  }

  .appendix_project {
    margin-bottom: 50px;
  }
  .appendix_name_div {
    margin-left: 145px;
  }

  .appendix_name {
    width: 146px;
    float: left;
    overflow: hidden;
    margin-left: 8px;
    word-wrap:break-word;
    text-align: center;
  }


  /*.el-form-item__label {*/
    /*margin-right: 30px;*/
  /*}*/




</style>



